package cn.sfrog.project.biz.web.controller;

import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.controller.BaseController;
import cn.sfrog.common.core.domain.ApiAjaxResult;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizUserRecharge;
import cn.sfrog.project.biz.admin.domain.BizUserRechargePayment;
import cn.sfrog.project.biz.admin.enums.PayMethodEnum;
import cn.sfrog.project.biz.admin.pay.PayFactory;
import cn.sfrog.project.biz.admin.service.IBizServiceOrderService;
import cn.sfrog.project.biz.admin.service.IBizUserRechargeService;
import cn.sfrog.project.biz.applet.config.AesUtil;
import cn.sfrog.project.biz.applet.config.WxPayConfig;
import cn.sfrog.project.biz.web.vo.account.AppPaymentQueryPayStatusVO;
import cn.sfrog.project.biz.web.vo.account.AppPaymentStatusVO;
import cn.sfrog.project.biz.web.vo.order.AppServiceOrderVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApiConfigKit;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/notify")
public class AppNotifyController extends BaseController {
    @Resource
    protected HttpServletRequest request;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    WxPayConfig wxPayConfig;
    @Autowired
    private IBizUserRechargeService bizUserRechargeService;
    @Autowired
    private IBizServiceOrderService bizServiceOrderService;
    /**
     * 支付回调接口
     * @return
     */
    @PostMapping("/payment/wxCallback")
    @ResponseBody
    @Transactional(rollbackFor = Throwable.class)
    public ApiAjaxResult wxCallback(){
        String xmlMsg = HttpKit.readData(request);
        System.out.println("*************回调信息:"+xmlMsg);
//        String xmlMsg = "{\"id\":\"56875fed-d1df-5aae-ba4f-bb1d7852034d\",\"create_time\":\"2024-01-16T20:59:51+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"TRANSACTION.SUCCESS\",\"summary\":\"支付成功\",\"resource\":{\"original_type\":\"transaction\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"1sZvlJAzwrRH8TU03FRWLQHFAS8REyIfxq9QHbECMi5zLNb0yMYTCjOtR8cHeZKbcEDN3biD2s00s92TF7viXl/6OdlM4b2UKZaDMNIoYbGIhezKH93eqk3caHvJTHB6y3uN5QCZZk6xTIBrwHVc7k/pQzU6Er45ChadupDDIrSb5inHnWyeYIFD88tHJfTXxhJuCh7I+8sHwyfLe+yhqf1jBKqppp1u4aoUboCHY6CnabcreAAokUpP80IP0ArI2s+xj9EOdcH28guTa1rS+JaOnTgfQWCdeOBQIRVzsljVSHMnlbzWnYU4IzeZrFv3VTKXn0ai1mmqacpj5Qd1oAMzWzEWKBkg0fX4+QY3a3SzAYyXKqgDXOEpXbbpvFk8yIvhsMpETiTg1o8sl8mPaL7SNspmeOI2wAo/2aEaDINaY/3dloKBc3UvDhFnkBOp64OAoB1KI2pveCVj6cg/f5oYh9caSXsCdTkBH+TxdHSQcpc0woVA71/ulzk0a+FxUCVI8sgqhaeA4EyYkn+Rnvl+Yr5lYCKmQeng17o60pJGtqWPIsbDS3dj2aEoP4llfA==\",\"associated_data\":\"transaction\",\"nonce\":\"8b0AFk632wc4\"}}";
        JSONObject obj = JSON.parseObject(xmlMsg);
        JSONObject resource = JSON.parseObject(obj.get("resource").toString());
        String associated_data = resource.get("associated_data").toString();
        Object ciphertext = resource.get("ciphertext");
        String nonce = resource.get("nonce").toString();
        String decryptData = null;
        try {
            decryptData = new AesUtil(wxPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8),
            nonce.getBytes(StandardCharsets.UTF_8),
            ciphertext.toString());
            JSONObject decryptDataObject = JSON.parseObject(decryptData);
            log.info("微信订单回调信息:{}",decryptData);
            if (!decryptDataObject.isEmpty()) {
                if("SUCCESS".equals(decryptDataObject.get("trade_state"))){
//                    BizUserRechargePayment payment = BizUserRechargePayment.DAO.selectById(decryptDataObject.get("out_trade_no").toString());
//                    if(StringUtils.isNull(payment)){
//                        throw new ApiException("查询不到支付流水");
//                    }
//                    //充值表
//                    LambdaQueryWrapper<BizUserRecharge> queryWrapper = new LambdaQueryWrapper<BizUserRecharge>()
//                            .eq(BizUserRecharge::getSerialNumber,payment.getRechargeSerialNumber());
//
//                    BizUserRecharge recharge = BizUserRecharge.DAO.selectOne(queryWrapper);
//                    if(StringUtils.isNull(recharge)){
//                        throw new ApiException("查询不到该充值记录");
//                    }
//                    if(!"0".equals(recharge.getPayStatus())){
//                        Map<String, String> xml = new HashMap<>(4);
//                        xml.put("return_code", "ERROR");
//                        xml.put("return_msg", "FAIL");
//                        return PaymentKit.toXml(xml);
//                    }
                    AppServiceOrderVO appServiceOrderVO = bizServiceOrderService.getServiceOrderByOrderNum(decryptDataObject.get("out_trade_no").toString());
                    if (appServiceOrderVO.getOrderStatus().equals("6")){
                        // 更新订单状态为3
                        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                        Date date = inputFormat.parse(decryptDataObject.get("success_time").toString());
                        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedDateTime = outputFormat.format(date);
                        HashMap hashMap = new HashMap();
                        hashMap.put("time",formattedDateTime);
                        hashMap.put("status","3");
                        hashMap.put("serviceOrderSn",decryptDataObject.get("out_trade_no").toString());
                        bizServiceOrderService.updateServiceOrderByOrderNum(hashMap);
                        System.out.println("hhhh");
                        // 支付成功 订单已经过期
                        // 退款
                    }else if(appServiceOrderVO.getOrderStatus().equals("2")){
                        // 更新订单状态为3
                        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                        Date date = inputFormat.parse(decryptDataObject.get("success_time").toString());
                        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedDateTime = outputFormat.format(date);
                        HashMap hashMap = new HashMap();
                        hashMap.put("time",formattedDateTime);
                        hashMap.put("status","3");
                        hashMap.put("serviceOrderSn",decryptDataObject.get("out_trade_no").toString());
                        bizServiceOrderService.updateServiceOrderByOrderNum(hashMap);
                    }
//                    System.out.println(appServiceOrderVO);
                    //微信支付
//                    payment.setPayType("1");
//                    payment.setPayTime(DateUtils.timestampToDate(decryptDataObject.get("success_time").toString()));
//                    //已支付
//                    payment.setPayStatus("1");
//                    payment.setSerialNumber(decryptDataObject.get("transaction_id").toString());//
//                    payment.setUpdateTime(new Date());
//                    payment.setUpdateBy(payment.getCreateBy());
//                    payment.updateById();
//
//                    //已支付
//                    recharge.setPayStatus("1");
//                    //线上支付
//                    recharge.setPaymentId(payment.getId());
//                    recharge.setUpdateTime(new Date());
//                    recharge.setUpdateBy(recharge.getCreateBy());
//                    recharge.updateById();
                    String key = Constants.APPLET_CACHE_PHONE_CODE_KEY + decryptDataObject.get("out_trade_no").toString();
                    boolean flage = redisCache.deleteObject(key);
                    if (flage){
                        log.info("删除小程序微信支付参数:{}",key);
                    }
                    Map<String, String> xml = new HashMap<>(4);
                    xml.put("return_code", "SUCCESS");
                    xml.put("return_msg", "OK");
                    return ApiAjaxResult.success(xml);
                }
//            // 订单号
//            System.out.println("订单号："+decryptDataObject.get("out_trade_no"));
//            // 支付状态
//            System.out.println("支付状态："+decryptDataObject.get("trade_state"));
//            // 中文支付状态
//            System.out.println("中文支付状态："+decryptDataObject.get("trade_state_desc"));
//            // 支付时间
//            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
//            Date date = inputFormat.parse(decryptDataObject.get("success_time").toString());
//            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String formattedDateTime = outputFormat.format(date);
//            System.out.println("支付时间："+formattedDateTime);
            }

        }  catch (Exception e) {
            throw new RuntimeException(e);
        }


        Map<String, String> xml = new HashMap<>(4);
        xml.put("return_code", "ERROR");
        xml.put("return_msg", "FAIL");
        return ApiAjaxResult.success(xml);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping(value = "/queryPayStatus")
    public ApiAjaxResult<AppPaymentStatusVO> queryPayStatus(AppPaymentQueryPayStatusVO query){
        return ApiAjaxResult.success(bizUserRechargeService.queryPayStatus(query));
    }



    @PostMapping(value = "/alipayNotify")
    public String alipayNotify(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> result = PayFactory.getPayService(PayMethodEnum.ALI_PAY).callback(request, response);
        return String.valueOf("回调接口返回数据====="+result.get("res")+"=======结束");
    }
}
